package com.zhou.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhou.entity.UserInfo;
import com.zhou.mapper.UserInfoMapper;
import com.zhou.service.UserInfoService;
import com.zhou.utils.Base64Util;
import com.zhou.utils.BeanChangeUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @Description :
 * @Author : zyy
 * @Date: 2024/7/19  11:37
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public String login(String phone, String password) throws Exception {
        if (BeanChangeUtils.isEmpty(phone) || BeanChangeUtils.isEmpty(password)) {
            return "手机号或密码不能为空";
        }
        //获取用户信息
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));
        //如果没有查到就走注册，有就走登录
        if (BeanChangeUtils.isEmpty(userInfo)) {
            //注册
            userInfo.setPhone(phone);
            //使用加密将密码加密在存入数据库
            try {
                byte[] bytes = Base64Util.decryBASE64(password);
                userInfo.setPassword(Arrays.toString(bytes));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            userInfoMapper.insert(userInfo);
        } else {
            //登录
            byte[] bytes = userInfo.getPassword().getBytes();
            String base64 = Base64Util.encryptBASE64(bytes);
            if (base64.equals(password)) {
                return userInfo.getId();
            } else {
                return "密码错误";
            }
        }
        return "登录成功";
    }

}
